package com.byx.imclientutil.netty;

import com.byx.imclientutil.protobuf.ChatMessageProtobuf;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;

/**
 * LoginAuthHandler
 *
 * @author Superb
 * @date 2021/4/4 16:52
 */
public class LoginAuthHandler extends ChannelInboundHandlerAdapter {
    private NettyWebSocketClientImpl imService;

    public LoginAuthHandler(NettyWebSocketClientImpl imService) {
        this.imService = imService;
    }

    /**
     * Calls {@link ChannelHandlerContext#fireChannelRead(Object)} to forward
     * to the next {@link ChannelInboundHandler} in the {@link ChannelPipeline}.
     * <p>
     * Sub-classes may override this method to change behavior.
     *
     * @param ctx
     * @param msg
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ChatMessageProtobuf.Msg message = (ChatMessageProtobuf.Msg) msg;
        if (message == null){
            return;
        }

        ChatMessageProtobuf.Msg handShakeMsg = imService.getHandshakeMsg();
        if (handShakeMsg == null){
            return;
        }

        if (handShakeMsg.getMessageType() == message.getMessageType()){
            System.out.println("握手认证中。。。"+message);

            ChatMessageProtobuf.Msg heartBeatMsg = imService.getHeartbeatMsg();
            if (heartBeatMsg == null){
                return;
            }
            System.out.println("发送心跳消息中，"+heartBeatMsg+"，心跳间隔为"+"ms");
            imService.sendMessage(heartBeatMsg);

            imService.addHeartBeatHandler();
        }else {
            ctx.fireChannelRead(msg);
        }
    }
}
